package link.jfire.socket.test;

import link.jfire.baseutil.simplelog.ConsoleLogFactory;
import link.jfire.baseutil.simplelog.Logger;
import link.jfire.jnet.common.buffer.ByteBuf;
import link.jfire.jnet.common.buffer.HeapByteBuf;
import link.jfire.jnet.common.buffer.HeapByteBufPool;
import link.jfire.jnet.common.decodec.FrameDecodec;
import link.jfire.jnet.common.exception.BufNotEnoughException;
import link.jfire.jnet.common.exception.LessThanProtocolException;
import link.jfire.jnet.common.exception.NotFitProtocolException;

public class LengthFrameDecodec implements FrameDecodec
{
    private Logger logger = ConsoleLogFactory.getLogger(ConsoleLogFactory.DEBUG);
    
    @Override
    public ByteBuf<?> decodec(ByteBuf<?> ioBuffer) throws NotFitProtocolException, BufNotEnoughException, LessThanProtocolException
    {
        logger.debug(ioBuffer.toString());
        if (ioBuffer.remainRead() == 0)
        {
            return null;
        }
        int length = ioBuffer.get();
        if (ioBuffer.remainRead() >= length)
        {
            HeapByteBuf result = HeapByteBufPool.getInstance().get(length);
            result.put(ioBuffer, length);
            ioBuffer.addReadIndex(length);
            return result;
        }
        else
        {
            return null;
        }
    }
    
}
